﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataAccessObject.DAO
{
    public class MonHocDAO
    {
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public List<MONHOC> getAllMonHoc()
        {
            using (QLHVEntities entity = new QLHVEntities())
            {
                return entity.MONHOCs.ToList();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="banhoc"></param>
        /// <returns></returns>
        public List<MONHOC_BAN> getMonHocByBanHoc(BANLOPHOC banhoc)
        {
            using (QLHVEntities entities = new QLHVEntities())
            {
                var monhoc_ban = (from data in entities.MONHOC_BAN
                            where data.BanLopHocId == banhoc.BanLopHocId
                            select data).ToList();
                var monhoc = entities.MONHOCs.ToList();
                if (monhoc_ban.Count < monhoc.Count)
                {
                    var list  = (from data in monhoc
                                where (from sub in monhoc_ban where sub.MonHocId == data.MonHocId select sub.MonHocId).Count<int>() == 0
                                select data).ToList();
                    foreach (var obj in list)
                    {
                        monhoc_ban.Add(new MONHOC_BAN() { MONHOC = obj, BanLopHocId = banhoc.BanLopHocId });
                    }                  
                }
                return monhoc_ban;           
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="monhoc"></param>
        /// <param name="listKhoiLop"></param>
        public void updateChiTietMonHocByMonHoc(MONHOC monhoc, List<KHOILOP> listKhoiLop)
        {
            using (QLHVEntities entities = new QLHVEntities())
            {
                var _monhoc = entities.MONHOCs.FirstOrDefault(p => p.MonHocId == monhoc.MonHocId);
                if (_monhoc == null) return;
                var chitietmonhocs = entities.CHITIETMONHOCs.Where(p => p.MonHocId == monhoc.MonHocId).ToList();
                foreach (var chitietmonhoc in chitietmonhocs)
                {
                    entities.CHITIETMONHOCs.DeleteObject(chitietmonhoc);
                }
                foreach (var khoilop in listKhoiLop)
                {
                    _monhoc.CHITIETMONHOCs.Add(new CHITIETMONHOC() { MonHocId = monhoc.MonHocId, KhoiLopId = khoilop.KhoiLopId });
                }
                entities.SaveChanges();
            }
        }
    }
}
